<?php
$listen = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
socket_bind($listen, '0.0.0.0', 9999);
socket_listen($listen);
$title="socket_fork";
cli_set_process_title( $title."-parent" );

for ($i = 0; $i < 5; $i++) {
    $pid = pcntl_fork();
    if (0 == $pid) {
        cli_set_process_title( $title."-child"."-".$i );
        while (true) {
            $sock_client = socket_accept($listen);
            if ($sock_client) {
                if (socket_getpeername($sock_client, $clinet_addr, $client_port)) {
                    echo " client:" . intval($sock_client) . " from  {$clinet_addr}:$client_port" . PHP_EOL;
                    sayWelcome($sock_client);
                }
                while (true) {
                    //接收到不少于10个的时候才返回
                    $len = socket_recv($sock_client, $buf, 10, MSG_WAITALL);
                    echo "recv:" . $buf . PHP_EOL;
                    socket_write($sock_client, $buf, $len);
                }
            } else {
                echo "client connect fail" . PHP_EOL;
            }
        }
    }
}
while($pid=pcntl_wait($status)){
    echo $pid." exit".PHP_EOL;
}
socket_close($sock_client);

function sayWelcome($client)
{
    $buf = date("H:i:s") . " welcome to server! you id:" . intval($client) . PHP_EOL;
    socket_write($client, $buf, strlen($buf));
}



